package com.saint.farmshop.Controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 聊天控制器
 *
 * @author Saint
 * @date 2022/06/11
 */
@Slf4j
@Component
@ServerEndpoint("/chat/{openId}")
public class WebSocketServer {

    private static int onlineCount = 0;

    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    private Session session;

    private String openId;

    @OnOpen
    public void onOpen(Session session, @PathParam("openId") String openId) {

        this.session = session;
        this.openId = openId;

        if(webSocketMap.containsKey(openId)) {
            webSocketMap.remove(openId);
        }

        webSocketMap.put(openId, this);

        addOnlineCount();

        log.info("有新连接加入，当前在线人数为：{}", getOnlineCount());

        sendMessage("连接成功");
    }

    @OnClose
    public void onClose() {

        if(webSocketMap.containsKey(openId)) {
            webSocketMap.remove(openId);
        }

        subOnlineCount();

        log.info("有一连接关闭，当前在线人数为：{}", onlineCount);
    }

    @OnMessage
    public void onMessage(String message,Session session) {

        log.info("来自客户端的消息：{}", message);

        JSONObject jsonObject = JSONObject.parseObject(message);

        jsonObject.put("openId", openId);

        String toOpenId = jsonObject.getString("toOpenId");

        if(webSocketMap.containsKey(toOpenId)) {
            webSocketMap.get(toOpenId).sendMessage(jsonObject.toJSONString());
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        onlineCount--;
    }


    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
